﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GameEngine.Scenes;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using GuiLibrary.layouts;

namespace GuiLibrary.Components
{
    public class Label: Component
    {
        public Text text;
        public List<Text> lines;
        public Element elementAssociated { get; set; }

        public Label(Component parent, Vector2 relPosition, Text text, Element elementAssociated) :
            base(parent, relPosition)
        {
            this.text = text;
            this.elementAssociated = elementAssociated;
        }

        public Label(Component parent, Text text) :
            this(parent, new Vector2(), text, null) { }


        public override void draw(SpriteBatch sb) 
        {
            Vector2 parentSize = parent.getSize(), textSize = getSize();
            if (parentSize.X >= textSize.X && parentSize.Y >= textSize.Y) //All is right with the world
            {
                text.draw(sb);
            }
            else// if(parentSize.X < textSize.X)
            {
                foreach (Text line in lines)
                    line.draw(sb);
            }
        }

        public override void update(int dTime) 
        {
            this.text.update(dTime);
            base.update(dTime);
        }

        public override void refresh() 
        {
            this.text.position = getPosition();
            this.text.text = parseText();
        }

        public override Vector2 getSize()
        {
            return text.font.MeasureString(text.text);
        }

        public void forceSize(Vector2 customSize) 
        {
            this.text.text = parseText(customSize);
        }

        private String parseText(Vector2 customSize) 
        {

            String line = String.Empty;
            String returnString = String.Empty;
            String[] wordArray = text.text.Split(' ');

            foreach (String word in wordArray)
            {
                if (text.font.MeasureString(line + word).Length() > customSize.X)
                {
                    returnString = returnString + line + '\n';
                    line = String.Empty;
                }

                line = line + word + ' ';
            }
            line = line.Substring(0, line.Length - 1);
            return returnString + line;
        }

        private String parseText()
        {
            Layout pl = ((Panel)parent).layout;
            Vector2 parentSize = parent.getSize() - new Vector2(pl.marginLeft + pl.marginRight, pl.marginTop + pl.marginDown);
            return parseText(parentSize);
        }
    }
}
